<?php

namespace App\Service\OpenShop\Merchant;

use App\Events\OpenShop\OrderEditedEvent;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExperienceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;

/**
 * 触发订单信息 已编辑事件用的
 */
class OrderEditedEventManager
{
    protected string $orderNo = '';
    protected int    $uid     = 0;

    protected $beforeUpdate;
    protected $beforeBase;
    protected $beforeIdentity;
    protected $beforeExperience;
    protected $beforeContract;

    protected $afterUpdate;
    protected $afterBase;
    protected $afterIdentity;
    protected $afterExperience;
    protected $afterContract;

    public function __construct(string $orderNo, int $uid)
    {
        $this->orderNo = $orderNo;
        $this->uid     = $uid;
    }

    public function recordOriginals()
    {
        $this->beforeUpdate     = OpenShopSignOrderModel::query()->where('orderNo', $this->orderNo)->first();
        $this->beforeBase       = OpenShopUserBaseInfoModel::query()->where('orderNo', $this->orderNo)->first();
        $this->beforeIdentity   = OpenShopUserIdentityCardModel::getDataByOrderNo($this->orderNo);
        $this->beforeExperience = OpenShopUserExperienceModel::getDataByOrderNo($this->orderNo);
        $this->beforeContract   = OpenShopUserContractModel::query()->where('orderNo', $this->orderNo)->first();
    }

    public function recordCurrent()
    {
        $this->afterUpdate     = OpenShopSignOrderModel::query()->where('orderNo', $this->orderNo)->first();
        $this->afterBase       = OpenShopUserBaseInfoModel::query()->where('orderNo', $this->orderNo)->first();
        $this->afterIdentity   = OpenShopUserIdentityCardModel::getDataByOrderNo($this->orderNo);
        $this->afterExperience = OpenShopUserExperienceModel::getDataByOrderNo($this->orderNo);
        $this->afterContract   = OpenShopUserContractModel::query()->where('orderNo', $this->orderNo)->first();
    }

    public function triggerEvent()
    {
        foreach (['beforeUpdate', 'beforeBase', 'beforeIdentity', 'beforeExperience', 'afterUpdate', 'afterBase', 'afterIdentity', 'afterExperience', 'beforeContract', 'afterContract'] as $key) {
            if (null === $this->{$key}) {
                $this->{$key} = [];
            } else {
                $this->{$key} = $this->{$key}->toArray();
            }
        }
        event(new OrderEditedEvent($this->beforeUpdate, $this->afterUpdate, $this->uid, $this->beforeBase, $this->afterBase, $this->beforeIdentity, $this->afterIdentity, $this->beforeExperience, $this->afterExperience, $this->beforeContract, $this->afterContract));
    }
}
